package club.vann.mock.web;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import lombok.Getter;

/**
 * 状态码：
 *
 * <ul>
 *   <li>SUCCESS
 *   <li>ERROR
 * </ul>
 */
@Getter
public enum HttpState {
  SUCCESS(200, "SUCCESS", "成功"),
  ERROR(500, "ERROR", "失败"),
  ;

  private final int code;
  private final String key;
  private final String message;
  private static final Map<Integer, HttpState> CODE_MAPPING;
  private static final Map<String, HttpState> KEY_MAPPING;

  static {
    CODE_MAPPING = new HashMap<>();
    KEY_MAPPING = new HashMap<>();
    for (HttpState httpState : HttpState.values()) {
      CODE_MAPPING.put(httpState.code, httpState);
      KEY_MAPPING.put(httpState.key, httpState);
    }
  }

  HttpState(int code, String key, String message) {
    this.code = code;
    this.key = key;
    this.message = message;
  }

  /**
   * 根据 code 获取 HttpState。
   *
   * @param code Code码值
   * @return HttpState
   */
  public static Optional<HttpState> getByCode(int code) {
    return Optional.ofNullable(CODE_MAPPING.get(code));
  }

  /**
   * 根据 key 获取 HttpState。
   *
   * @param key Key值
   * @return HttpState
   */
  public static Optional<HttpState> getByKey(String key) {
    return Optional.ofNullable(KEY_MAPPING.get(key));
  }
}
